package cn.tedu.rtc.controller;

import cn.tedu.rtc.mqtt.model.ChannelName;
import cn.tedu.rtc.mqtt.model.CommonTopicReceiver;
import cn.tedu.rtc.mqtt.model.CommonTopicResponse;
import cn.tedu.rtc.mqtt.model.EventsMethodEnum;
import cn.tedu.rtc.mqtt.service.gateway.IMqttMessageGateway;
import cn.tedu.rtc.mqtt.service.messagesender.IMessageSenderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.MessageHeaders;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

@RestController
@RequestMapping("/mqtt")
@Api(tags = "MQTT 访问控制")
public class MqttController {

    @Autowired
    private IMessageSenderService messageSender;
    @Autowired
    private IMqttMessageGateway messageGateway;

    @PostMapping("/sendMqtt")
    @ApiOperation("向指定主题中发送消息")
    public ResponseEntity<String> sendMqtt(@RequestParam("topic") String topic, @RequestParam("data") String data) {
        try {
            CommonTopicResponse response = CommonTopicResponse.builder()
                    .tid(UUID.randomUUID().toString())
                    .bid(UUID.randomUUID().toString())
                    .data(data)
                    .timestamp(System.currentTimeMillis())
                    .build();
            messageSender.publish(topic, response);
            return new ResponseEntity<>("send success.", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("send failed.", HttpStatus.BAD_REQUEST);
        }
    }

    @PostMapping("/send-mqtt")
    @ApiOperation("向指定主题中发送消息")
    public ResponseEntity<String> send_mqtt(@RequestParam("topic") String topic, @RequestParam("data") String data) {
        try {
            messageGateway.publish(topic, data.getBytes(StandardCharsets.UTF_8));
            return new ResponseEntity<>("send success.", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("send failed.", HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 发送消息格式：
     * topic: thing/product/8888/events
     * payload: {
     * "tid":"6a7bfe89-c386-4043-b600-b518e10096cc","bid":"42a19f36-5117-4520-bd13-fd61d818d52e","timestamp": 1598411295123,"needReply": 1,"gateway":"sn","method": "device_b","data": {"time": 123}
     * }
     *
     * @param receiver
     * @param headers
     * @return
     */
    @ServiceActivator(inputChannel = ChannelName.INBOUND_EVENTS_CONTROL, outputChannel = ChannelName.OUTBOUND_EVENTS)
    public CommonTopicReceiver handleControl(CommonTopicReceiver receiver, MessageHeaders headers) {
        EventsMethodEnum eventsMethodEnum = EventsMethodEnum.find(receiver.getMethod());
        // 如果返回receiver，则进入OUTBOUND_EVENTS通道进行下一步处理；返回null则终止
        if (eventsMethodEnum == EventsMethodEnum.DEVICE_A) {
            return receiver;
        } else if (eventsMethodEnum == EventsMethodEnum.DEVICE_B) {
            return null;
        }
        return null;
    }

}